package com.aidisp.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aidisp.exception.UserException;
import com.aidisp.model.admin.User;
import com.aidisp.service.UserService;
import com.aidisp.util.StringUtil;

@Controller
@RequestMapping("user")
public class UserController {
	private static final Logger logger = Logger.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@RequestMapping(value="register",method=RequestMethod.POST)
	@ResponseBody
	public void register(@ModelAttribute User user){
		user.setAvailable(true);
		user.setCreateTime(System.currentTimeMillis());
		user.setLocked(false);
		userService.add(user);
		System.out.println("register");
	}
	@RequestMapping(value="login",method=RequestMethod.POST)
	@ResponseBody
	public String login(@ModelAttribute User user,HttpServletRequest request,ModelMap modelMap){
		logger.debug("start execute login");
		logger.debug("user info loginName:"+user.getLoginName()+",password:"+user.getPassword());
		User loginUser = userService.findUserLogin(user);
		if(loginUser!=null){
			if(!loginUser.isAvailable()){
				throw new UserException("帐号已停用",UserException.ACCOUNT_DISABLE);
			}
			boolean flag = false;
			//判断用户是否处于锁定状态并且解锁时间小于等于系统时间
			if(loginUser.isLocked()){
				if(loginUser.getUnlockTime()<=System.currentTimeMillis()){
					flag = true;
				}
			}else{
				flag = true;
			}
			//是否可执行登录
			if(flag){
				//判断密码是否匹配
				if(loginUser.getPassword().equals(StringUtil.md5(user.getPassword()))){
					//记录登录IP地址
					loginUser.setLastLoginIp(request.getRemoteAddr());
					//记录最后一次登录时间
					loginUser.setLastLoginTime(System.currentTimeMillis());
					//记录登录次数
					loginUser.setLoginCount(loginUser.getLoginCount()+1);
					//错误输入密码次数归零
					loginUser.setPasswordErrorCount(0);
					//帐号锁定次数归零
					loginUser.setLockedCount(0);
					//设置是否被锁定
					loginUser.setLocked(false);
					userService.edit(loginUser);
				}else{
					String message = "密码错误";
					//错误输入密码次数加一
					loginUser.setPasswordErrorCount(loginUser.getPasswordErrorCount()+1);
					//错误输入密码次数是否超过三次
					if(loginUser.getPasswordErrorCount()>=3){
						//锁定帐号
						loginUser.setLocked(true);
						//设置解锁时间
						loginUser.setUnlockTime(System.currentTimeMillis()+1000*60*30);
						//设置帐号被锁定的次数
						loginUser.setLockedCount(loginUser.getLockedCount()+1);
						message = "密码错误输入三次,帐号锁定30分钟";
						//帐号被锁定超过3次,停用帐号
						if(loginUser.getLockedCount()>=3){
							message = "多次密码输入错误,帐号被停用";
							loginUser.setAvailable(false);
						}
					}
					userService.edit(loginUser);
					throw new UserException(message,UserException.PASSWORD_ERROR);
				}
			}else{
				long unlockTime = (loginUser.getUnlockTime()-System.currentTimeMillis())/1000*60;
				throw new UserException("帐号被锁定,请在"+(unlockTime>1?unlockTime:1)+"分钟后重试",UserException.ACCOUNT_LOCKED);
			}
		}else{
			throw new UserException("用户不存在",UserException.USER_NOT_EXIST);
		}
		request.getSession().setAttribute("user", loginUser);
		return "login.html";
	}
	@InitBinder
	private void dataConver(WebDataBinder binder){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}
}
